package com.ruoyi.media.service.impl;

import com.drew.imaging.ImageMetadataReader;
import com.drew.lang.GeoLocation;
import com.drew.metadata.Metadata;
import com.drew.metadata.exif.ExifSubIFDDirectory;
import com.drew.metadata.exif.GpsDirectory;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.media.domain.Categories;
import com.ruoyi.media.domain.Images;
import com.ruoyi.media.domain.dto.ImagesDTO;
import com.ruoyi.media.service.DataFileService;
import com.ruoyi.media.service.FileStorageService;
import com.ruoyi.media.service.ICategoriesService;
import com.ruoyi.media.service.IImagesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Collection;
import java.util.Date;
import java.util.Objects;

@Slf4j
@Service
public class DataFileServiceImpl implements DataFileService {

    private static final Integer PRIVATE_SETTINGS = 0;
    private static final Integer PUBLIC_SETTINGS = 1;

    @Autowired
    private IImagesService imageService  ;
    @Autowired
    private ICategoriesService categoriesService;


    @Autowired
    private FileStorageService fileStorageService;

    @Override
    public String uploadImgFile(MultipartFile file, ImagesDTO imagesDTO) {
        //参数处理
        LocalDateTime captureTime = null ;
        Double longitude = null;
        Double latitude = null;
        String extension = null;
        String url = null;
        try  {
            //获取图片媒体对象
            Metadata metadata = ImageMetadataReader.readMetadata(file.getInputStream());
            //获取图片的拍摄时间
            ExifSubIFDDirectory directory = metadata.getFirstDirectoryOfType(ExifSubIFDDirectory.class);
            if(!Objects.isNull(directory)){
                Date date = directory.getDate(ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL);
                 if(!Objects.isNull(date))
                // 将 Date 转换为 LocalDateTime
                    captureTime = dateToLocalDateTime(date);
            }

            Collection<GpsDirectory> gpsDirectories = metadata.getDirectoriesOfType(GpsDirectory.class);
            for(GpsDirectory gps : gpsDirectories) {
                //获取图片的经纬度信息
                GeoLocation geoLocation = gps.getGeoLocation();
                longitude = geoLocation.getLongitude();
                latitude = geoLocation.getLatitude();
            }

            url = fileStorageService.uploadImgFile("", file.getOriginalFilename(), file.getInputStream());
            String fileName = file.getOriginalFilename();
//            获取后缀名
            if(StringUtils.isNotEmpty(fileName))
                extension = fileName.substring(fileName.lastIndexOf(".") + 1);

//            fileName = imagesDTO.getFileName() != null ? imagesDTO.getFileName() : fileName;

            imagesDTO.setCaptureTime(captureTime);
            imagesDTO.setImageType(extension);
            imagesDTO.setDescription("");
            imagesDTO.setLatitude(latitude);
            imagesDTO.setLongitude(longitude);
            imagesDTO.setStoragePath(url);
            imagesDTO.setUploadTime(LocalDateTime.now());
            imagesDTO.setFileName(fileName);
            imagesDTO.setPrivacySetting(PUBLIC_SETTINGS);
            imagesDTO.setUserId(SecurityUtils.getUserId());
            imagesDTO.setCategoryId(imagesDTO.getCategoryId());

            //查询分类信息
            Categories categories = categoriesService.selectCategoriesByCategoryId(imagesDTO.getCategoryId());
            imagesDTO.setCategoryName(categories.getName());
            //保存图片信息
            imageService.insertImages(imagesDTO);
        } catch (Exception e) {
            // 处理文件读取异常
            return null;
        }

        return url;

    }

    @Override
    public void imageDownload(Long id, HttpServletResponse response) {
        //1、获取图片url
        Images images = imageService.selectImagesById(id);

        if(Objects.isNull(images)){
            return;
        }
        //2、minio下载图片
        byte[]  imageData = fileStorageService.downLoadFile(images.getStoragePath());
        //3、判断是否下载成功
        if(Objects.isNull(imageData)){
            log.error("图片下载失败,id: {}", id);
            return;
        }
        //4、成功返回

        response.setContentType("application/octet-stream");
        response.setContentLength(imageData.length);
        try (OutputStream os = response.getOutputStream()) {
            os.write(imageData);
            os.flush();
        } catch (IOException e) {
            // 处理异常
            log.error("图片下载失败", e);
        }

    }


    /**
     * 将 Date 转换为 LocalDateTime
     * @param date
     * @return
     */
    private static LocalDateTime dateToLocalDateTime(Date date) {
        // 将 Date 转换为 Instant
        Instant instant = date.toInstant();

        // 指定时区（例如 UTC+8）
        ZoneId zoneId = ZoneId.of("Asia/Shanghai");

        // 将 Instant 转换为 LocalDateTime
        return LocalDateTime.ofInstant(instant, zoneId);
    }
}
